import wx from 'weixin-js-sdk'
import sha1 from 'sha1'
import Rest from './http/rest'

var saFun = {
  getRandomStr: function (len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; //默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
    var maxPos = chars.length;
    var str = '';
    for (let i = 0; i < len; i++) {
      str += chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return str
  },

};
var saBs = {
  weixinAppid: 'wx07643ac520446c5e',
  host: Rest.apiHost,
  path: '/newfcty/h5/jn/get.hx'

};

var ShareUtil = {


  //微信分享
  shareWx: function (funcList, callback)  {

    this.getAccessToken().then((accessToken) => {
      if (!accessToken) return;
      this.getTicket(accessToken).then((jsapiTicket) => {
        if (!jsapiTicket) return;
        let randomStr = saFun.getRandomStr(32);
        let nowDate = +new Date()
        let time = Math.round(nowDate / 1000);//13位时间戳转10位
        let ticket = 'jsapi_ticket=' + jsapiTicket + '&noncestr=' + randomStr + '&timestamp=' + time + '&url=' + (location.href.split('#')[0]);
        if (!funcList) {
          return false
        }

        wx.config({
          debug: false,
          appId: saBs.weixinAppid, // 必填，公众号的唯一标识
          timestamp: time, // 必填，生成签名的时间戳
          nonceStr: randomStr, // 必填，生成签名的随机串
          signature: sha1(ticket),// 必填，签名，见附录1
          jsApiList: funcList
        });
        wx.ready(function () {
          if (callback) callback()
        })

      })
    })

  },
  //获取token
  getAccessToken: async function() {
    let requestData = encodeURIComponent('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + saBs.weixinAppid + '&secret={secret}');
    let res = await Rest.get(saBs.host + saBs.path + '?url=' + requestData);
    console.log('getToken', res);
    let data = JSON.parse(res.data.data);
    if (null != data && '' != data) {
      return data.access_token
    } else {
      return null
    }
  },
  //获取ticket
  getTicket: async function(accessToken) {

    let requestTicket = encodeURIComponent('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + accessToken + '&type=jsapi');
    let res = await Rest.get(saBs.host + saBs.path + '?url=' + requestTicket);
    let data = JSON.parse(res.data.data);
    if (null != data && '' != data) {
      return data.ticket
    } else {
      return null
    }
  },
};

export {ShareUtil}



